package com.kfm.base.net;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TCPServer {

    public static void main(String[] args) {
        try {
            ServerSocket server = new ServerSocket(8888);

            ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(5, 40, 0L, TimeUnit.NANOSECONDS, new ArrayBlockingQueue<>(50), new ThreadPoolExecutor.AbortPolicy());

            while(true){
                // 阻塞，等待客户端连接.连接一建立，就会返回连接对象 Socket
                Socket client = server.accept();

                poolExecutor.execute(() -> {
                    // socket 就是客户端对象, 获取客户端发送的内容

                    try(InputStream inputStream = client.getInputStream();) {
                        byte[] bytes = inputStream.readAllBytes();
                        String msg = new String(bytes);

                        System.out.println("接收到" + client.getInetAddress() + " 的信息：" + msg);

                        client.getOutputStream().write("hello".getBytes());

                        client.getOutputStream().close();

                        client.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                });
            }



        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
